package com.bawei.demo_shoppingcar.fragment;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bawei.demo_shoppingcar.R;
import com.bawei.demo_shoppingcar.activity.UserRegisterActivity;
import com.bawei.demo_shoppingcar.adapter.CarDBAdapter;
import com.bawei.demo_shoppingcar.application.ContentData;
import com.bawei.demo_shoppingcar.application.TopApp;
import com.bawei.demo_shoppingcar.bean.ShoppingDBbean;
import com.bawei.demo_shoppingcar.db.ShoppingDBUtils;
import com.bawei.demo_shoppingcar.view.SlideCutListView;

import java.io.File;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ShoppingCarFragment extends Fragment implements View.OnClickListener {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    private ImageView imageView;
    //    private ListView listView;
    private ArrayList<ShoppingDBbean> shoppingList;
    private RelativeLayout relativeLayout_view;
    private CarDBAdapter adapter;
    private Button clickAll;
    private Button clickTurn;
    private TextView total_price;
    private AlertDialog.Builder alertDialog;
    private ShoppingDBUtils dbUtils;
    private SlideCutListView slideCutListView;


    //    private ArrayAdapter<String> adapter;
    private List<String> dataSourceList = new ArrayList<String>();
    private Button shopping_bt_buy;
    private AlertDialog.Builder buyDialog;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            buyDialog.create();
        }
    };
    private TextView buy_text;


    public ShoppingCarFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_shopping_car, container, false);
        boolean login_qq = ContentData.isLogin_QQ();
        if (!login_qq) {
            //未登陆  跳转登陆页面
            startActivity(new Intent(getActivity(), UserRegisterActivity.class));
        } else {
            initView(inflate);
            dbUtils = ShoppingDBUtils.getInstance(getContext());
            setisHide();

        }

        slideCutListView.setRemoveListener(new SlideCutListView.RemoveListener() {
            @Override
            public void removeItem(SlideCutListView.RemoveDirection direction, final int position) {
                //TODO  滑动删除也会调用长按点击事件  -----  没解决
                ShoppingDBbean shoppingDBbean = shoppingList.get(position);
                int id1 = shoppingDBbean.getId();
                dbUtils.deleteData(id1);
                setisHide();
                Toast.makeText(getContext(), "已经删除  ", Toast.LENGTH_SHORT).show();
            }
        });

        slideCutListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                alertDialog = new AlertDialog.Builder(getContext());
                alertDialog.setTitle("请选择:");
                alertDialog.setMessage("是否删除?");
                alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        ShoppingDBbean shoppingDBbean = shoppingList.get(position);
                        int id1 = shoppingDBbean.getId();
                        dbUtils.deleteData(id1);
                        setisHide();
                    }
                });
                alertDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                alertDialog.show();

                return true;
            }
        });
        slideCutListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                ShoppingDBbean shoppingDBbean = shoppingList.get(position);
                shoppingDBbean.setPitch(!shoppingDBbean.isPitch());
                setListViewData();
                totalPrice();

            }
        });


        return inflate;
    }

    //全选
    public void clickAll() {
        for (int i = 0; i < shoppingList.size(); i++) {
            ShoppingDBbean shoppingDBbean = shoppingList.get(i);
            shoppingDBbean.setPitch(true);
        }
        adapter.notifyDataSetChanged();
    }

    //反选
    public void clickTurn() {

        for (int i = 0; i < shoppingList.size(); i++) {
            ShoppingDBbean shoppingDBbean = shoppingList.get(i);
            shoppingDBbean.setPitch(!shoppingDBbean.isPitch());
        }
        adapter.notifyDataSetChanged();
    }


    private void setListViewData() {

        //设置适配器
        adapter = new CarDBAdapter(getContext(), shoppingList);

        slideCutListView.setAdapter(adapter);

        if (shoppingList != null && shoppingList.size() >= 0) {
            totalPrice();
        }


    }

    //判断是否显示
    private void setisHide() {

        shoppingList = dbUtils.queryData();
        if (shoppingList.size() == 0) {
            //没有数据
            imageView.setVisibility(View.VISIBLE);
            relativeLayout_view.setVisibility(View.GONE);
        } else {
            imageView.setVisibility(View.GONE);
            relativeLayout_view.setVisibility(View.VISIBLE);
        }
        setListViewData();
    }

    private void initView(View inflate) {

        slideCutListView = (SlideCutListView) inflate.findViewById(R.id.slideCutListView);
        //立即购买
        shopping_bt_buy = (Button) inflate.findViewById(R.id.shopping_bt_buy);

        imageView = (ImageView) inflate.findViewById(R.id.shopping_Image);
//        listView = (ListView) inflate.findViewById(R.id.shopping_listView);
        total_price = (TextView) inflate.findViewById(R.id.shopping_total_price);
        relativeLayout_view = (RelativeLayout) inflate.findViewById(R.id.shopping_view);
        clickAll = (Button) inflate.findViewById(R.id.clickAll);
        clickTurn = (Button) inflate.findViewById(R.id.clickTurn);
        clickAll.setOnClickListener(this);
        clickTurn.setOnClickListener(this);
        shopping_bt_buy.setOnClickListener(this);
//        listView.setOnItemClickListener(this);
//        listView.setOnItemLongClickListener(this);
    }


    //设置总价
    public float totalPrice() {
        float num_price = 0;
        for (int i = 0; i < shoppingList.size(); i++) {
            ShoppingDBbean shoppingDBbean = shoppingList.get(i);
            boolean pitch = shoppingDBbean.isPitch();
            if (pitch) {
                num_price += shoppingDBbean.getNum() * shoppingDBbean.getShopping_price();
            }
            total_price.setText("总价:" + num_price + "元");
        }
        return num_price;
    }

    //未登陆  跳转登陆页面
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            boolean login_qq = ContentData.isLogin_QQ();
            if (!login_qq) {
                startActivity(new Intent(getActivity(), UserRegisterActivity.class));
            } else {
                setisHide();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.clickAll:
                clickAll();
                break;
            case R.id.clickTurn:
                clickTurn();
                break;
            case R.id.shopping_bt_buy:

                setBuyDiaLog();

                break;
        }
        totalPrice();

    }

    //立即购买
    private void setBuyDiaLog() {

        int num = 0;
        if (shoppingList.size() != 0) {
            int size = shoppingList.size();
            for (int i = 0; i < size; i++) {
                ShoppingDBbean shoppingDBbean = shoppingList.get(i);
                boolean pitch = shoppingDBbean.isPitch();
                if (pitch) {
                    int id = shoppingDBbean.getId();
                    dbUtils.deleteData(id);
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                    String str = formatter.format(curDate);
                    String record = "您于\n" + str + "\n购买了\n" + shoppingDBbean.getShopping_name() + "\n" + shoppingDBbean.getNum() + "个\n" +
                            " 一共花费了\n" + shoppingDBbean.getShopping_price() + " 元\r\n";
                    writeFileToSD(record);
                    num++;
                }
            }
        }
        if (num != 0) {
            buyDialog = new AlertDialog.Builder(getContext());
            View view = LayoutInflater.from(getContext()).inflate(R.layout.buy_dialog, null);
            buy_text = (TextView) view.findViewById(R.id.buy_text);
            String string = totalPrice() + "";
            buy_text.setText("您在  " + TopApp.addrStr + " 消费了 " + string + " 元");
            buyDialog.setView(view);
            buyDialog.show();
            Toast.makeText(getContext(), "购买成功", Toast.LENGTH_SHORT).show();
            setisHide();
        } else {
            Toast.makeText(getContext(), "请选择商品", Toast.LENGTH_SHORT).show();
        }
    }
/*

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ShoppingDBbean shoppingDBbean = shoppingList.get(position);
        shoppingDBbean.setPitch(!shoppingDBbean.isPitch());
        setListViewData();
        totalPrice();

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

        alertDialog = new AlertDialog.Builder(getContext());
        alertDialog.setTitle("请选择:");
        alertDialog.setMessage("是否删除?");
        alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                ShoppingDBbean shoppingDBbean = shoppingList.get(position);
                int id1 = shoppingDBbean.getId();
                dbUtils.deleteData(id1);
                setisHide();
            }
        });
        alertDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        alertDialog.show();
        return true;
    }
*/


    //使用RandomAccessFile 写文件 还是蛮好用的..推荐给大家使用...
    public void writeFileToSD(String context) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {

            return;
        }
        Log.d("TestFile", sdStatus);
        try {
            String pathName = "/sdcard/";
            String fileName = "log.txt";
            File path = new File(pathName);
            File file = new File(pathName + fileName);
            if (!path.exists()) {
                path.mkdir();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.seek(file.length());
            raf.write(context.getBytes());
            raf.close();
            //注释的也是写文件..但是每次写入都会把之前的覆盖..
          /*  String pathName = "/sdcard/";
            　String fileName = "log.txt";
            　File path = new File(pathName);
            　File file = new File(pathName + fileName);
            　if (!path.exists()) {
                　　Log.d("TestFile", "Create the path:" + pathName);
                　　path.mkdir();
                　}
            　if (!file.exists()) {
                　　Log.d("TestFile", "Create the file:" + fileName);
                　　file.createNewFile();
                　}
            　FileOutputStream stream = new FileOutputStream(file);
            　String s = context;
            　byte[] buf = s.getBytes();
            　stream.write(buf);
            　stream.close();*/
        } catch (Exception e) {
            Log.e("TestFile", "Error on writeFilToSD.");
        }
    }


}
